<template>
	<view class="mlvb-boss">
		<view class="mlvb-layer">
			<!-- 直播视频 -->
			<!-- <view v-if="!pureAudio" class="group-top-video">
				<view class="left">
					<view>{{itemRoom.groupName}}</view>
					<view>在线: {{itemRoom.onlineNum}} > </view>
					<view>连线中: 00:00:00</view>
				</view>
				<view class="right">
					{{itemRoom.language}}
				</view>
			</view> -->

			<!-- 直播音频 -->
			<!-- 	<view v-if='pureAudio' class="group-top-voice">
				<view>{{itemRoom.groupName}}</view>
				<view class="voice-c">讲台上: 00:00:00</view>
				<view class="voice-right">
					<view>{{itemRoom.language}}</view>
				</view>
				<view>在线: {{itemRoom.onlineNum}} > </view>
			</view> -->


			<mlvb-live-room 
			id="id_liveroom" 
			:roomid="roomID" 
			:roleL="role" 
			:roomname="roomName" 
			:beauty="beauty" 
			template="float"
			@RoomEvent="onRoomEvent" 
			:mutedPlayer="mutedPlayer" 
			bindonRoomEvent="onRoomEvent"
			:mutedPusher='mutedPusher' 
			:debug="debug" 
			:pureaudio="pureAudio"
			:canvasAud="canvasAud" 
			:chatList="chatList" 
			:chatMixed='chatMixed' 
			:itemRoom='itemRoom' 
			:anchorLock='anchorLock'
			:isZoom='isZoom' 
			:payRoomId='itemRoom.payRoomId' 
			:chatTop='chatTop' 
			:isStart='isStart' 
			:isLink='isLink' 
			:isBut='isBut'>
			
			</mlvb-live-room>
		</view>

		<!-- 聊天区域 -->
		<!-- item-chat small -->
		<!-- 		<view v-if='!isZoom' class="live-chat" ref="liveChat">
			<scroll-view scroll-y="true" style="height: 270rpx;" :scroll-top="scrollTop">
				
				<view :class="item.message.length > 20 ? 'item-chat big chat-top' : 'small chat-top'" v-for="(item, index) in chatList"
				 :key='index'>
					<text class="text-one" v-show="item.message.length > 20 ">{{item.name}}: </text>
					<text class="text-two" v-show="item.message.length > 20 ">{{item.message}}</text>
					<text class="text-three" v-show="item.message.length < 20 ">
						{{item.name}}: {{item.message}}
					</text>
				</view>
			</scroll-view>
		</view>
 -->

		<!-- 底部操作按钮 -->
		<!--   -->

		<view @animationend='inputEnd' :style="isBut?'display:none;':''" :class="isFocus ? 'show-view' : 'hide-view'">
			<input v-model="chat" class="input-chat" type="text" :value="chat" :hold-keyboard='true' @blur='inputBlur' :focus='isFocus' />
			<button @click="sendButton" class="send-chat" type="primary">发送</button>
		</view>

		<!-- <view class="mlvb-button" v-if="!isZoom && isBut" :class="isBut ? 'show-button': ''">
			<view class="view-button">
				<image @click="isMutedPusher" :src=" !mutedPusher? 'http://www.huihejituan.com/tripPictstorage/qmore/wx/a06ca1af961f475747c22efc1b635a1.png': 'http://www.huihejituan.com/tripPictstorage/qmore/wx/e90a576adbb11a8cf3f69b97c39cbae.png'"></image>
				<image @click="isMutedPlayer" :src=" !mutedPlayer ? 'http://www.huihejituan.com/tripPictstorage/qmore/wx/732d8a7cb59e2dd81e24fca76964045.png':'http://www.huihejituan.com/tripPictstorage/qmore/wx/c893b0a95857ac3cbb5407ad7964627.png'"
				 mode=""></image>

			</view>
			<image v-if="role == 'anchor'" @click="start" class="start-button" :src="isStart?'http://www.huihejituan.com/tripPictstorage/qmore/wx/show.png':'http://www.huihejituan.com/tripPictstorage/qmore/wx/sowing.png'"></image>
			<image v-else @click="start" class="start-button" :src="isStart ? 'http://www.huihejituan.com/tripPictstorage/qmore/wx/lianxian.png' : 'http://www.huihejituan.com/tripPictstorage/qmore/wx/0ebe3254b394d73f8c1e2b1ef4a83a9.png'"></image>

			<view class="view-button">
				<image @click="onShowGift" src="http://www.huihejituan.com/tripPictstorage/qmore/wx/93228606b9c927ae5dd07cadc0ada17.png"
				 mode=""></image>

				<image @click="imgFocus" src="http://www.huihejituan.com/tripPictstorage/qmore/wx/f2f6147235f22dc4829c86e2dcf2dd1.png"
				 mode=""></image>
			</view>
		</view> -->

		<cover-view class="cat-gift" v-show="isShowGift">
			<cover-view class="gift-num" v-show="isShowNum">
				<cover-view @click="onGiftNum(item)" class="item-num" v-for="(item,index) in giftNumberList" :key='index'>{{item}}</cover-view>
			</cover-view>
			<cover-view class="cat-top">
				<cover-view class="item-top">
					<cover-view>猫币剩余：</cover-view>
					<cover-view>{{catCoin}}</cover-view>
				</cover-view>
				<cover-view class="item-top">礼物</cover-view>
				<cover-view class="item-top">
					<cover-image src="/static/diqiuquan/wenti.png"></cover-image>
				</cover-view>
			</cover-view>

			<cover-view class="gift">
				<cover-view class="gift_item" v-for="(item,index) in giftList" :key="index" :class="{active1:menuIndex==index}"
				 @tap="chooseGift(index,item)">
					<cover-image :src="item.pic" mode=""></cover-image>
					<cover-view class="text1">{{item.gift_name}}</cover-view>
					<cover-view class="text2">猫币*{{item.amount}}</cover-view>
				</cover-view>
			</cover-view>

			<cover-view class="send">
				<cover-view class="group-gift" @click="onGroupGift">
					<cover-image :src="!isGroupGift ? '../../../static/jingjie/weixuanzhong.png' : '../../../static/jingjie/xuanzhong.png'"></cover-image>
					<cover-view>全体组员</cover-view>
				</cover-view>
				<cover-view class="item-send">
					<cover-image :class="isShowNum ? 'isRotate' : 'backRotate'" @click="onSendNum" src="../../../static/jingjie/xiajiantou.png"></cover-image>
					<cover-view @click="onSendNum">{{giftNum}}</cover-view>
					<cover-view class="onSend" @click="onSend">发送</cover-view>
				</cover-view>
			</cover-view>
		</cover-view>
	</view>
</template>

<script>
	import COS from 'cos-wx-sdk-v5'
	import TIM from 'tim-wx-sdk'
	export default {
		data() {
			return {
				component: '',
				roomID: '',
				groupId:'',
				roomName: '',
				beauty: 5, //美颜级别0 - 5
				role: 'audience', //anchor 代表主播，audience 代表观众
				pureAudio: false, //是否开启纯音频推流
				mutedPlayer: false, //观众是否收听主播声音
				mutedPusher: false, // 主播是否推送声音
				debug: true,
				liveroom: '',
				user_info: '',
				type: '',
				option: '',
				userName: '',
				rooms: [],
				itemRoom: {},
				isStart: true,
				tim: '',
				canvasAud: 'anchor',
				imgAddress: [false, false, false, false, false],
				messageNum: 0,
				chatList: [],
				scrollTop: '10',
				isFocus: false,
				isBut: true,
				chat: '',
				chatMixed: {},
				addNumber: 0,
				smallCaster: false,
				anchorLock: {
					cmd: 'AnchorLock',
					msg: {}
				},
				isZoom: false,
				giftList: [],
				catCoin: '',
				menuIndex: 0,
				giftNumberList: [520, 188, 99, 66, 30, 10, 6, 1],
				isShowNum: false,
				giftNum: 1,
				isShowGift: false,
				giftMoney: 0,
				paymentId: 0,
				isGroupGift: false,
				chatTop: 'msg-9',
				isLink: true,
				t: 0,
				onlinenums:[],
				ChangeStuts:1,
				IsInterview:false,
				WeekToId:'',
			}
		},
		computed: {
			labelTitle() {
				return this.itemRoom.label
			}
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
		        console.log(res.target)
		    }
		    return {
		        title: '我正在Q莫学习外语，你也一起来参加吧',
		        path: '/pages/Meet/MLVBRoom/MLVBRoom'
		    }
		  },
		onShow:function(){
			const pages = getCurrentPages()
			const currPage = pages[pages.length - 1]
			console.log(currPage.data,'获取的数据')
			this.IsInterview = currPage.data.IsInterview
			this.WeekToId = currPage.data.user_id
			setTimeout(() => {
				let self = this
				self.sendChat({
					data: {
						cmd: '2',
						msg: '进入房间'
					},
					userAvatar: self.user_info.avatar,
					userName: self.userName || wx.getStorageSync('user_id'),
					cmd: "CustomCmdMsg"
				}, false)
			}, 2000)
			this.IsInterviewWheat()//邀请连麦
		},
		onLoad(options) {
			this.option = options
			this.user_info = uni.getStorageSync('user_info')
			this.roomID = options.roomID //直播间群号
			this.groupId = options.groupId
			this.role = uni.getStorageSync('user_id') == uni.getStorageSync('liveAnchorID') ? 'anchor' : 'audience'
			this.roomName = options.roomName
			this.userName = options.userName
			this.pureAudio = JSON.parse(options.pureAudio)
			this.itemRoom = JSON.parse(options.itemRoom)
			console.info(this.itemRoom.payRoomId,'怎么回事')
			this.catCoin = this.user_info.cat_coin
			uni.setNavigationBarTitle({
				title: this.itemRoom.label
			})
			wx.setStorageSync('closeAddress', false)
			wx.setStorageSync('isCaster', false)
			this.getRoomMember()
			this.linkIM()
			this.getgiftList()
			this.chatMixed = {
				cmd: 'AnchorIndex',
				msg: {
					"0": {
						avatar: this.user_info.avatar,
						userId: wx.getStorageSync('user_id').toString(),
						nickName: this.userName || wx.getStorageSync('user_id').toString()
					}
				}
			}
			this.getonline()//获取在线人数
			this.ChangeOnline()//更改在线状态
			
		},
		watch: {
			chatList(newV, oldV) {
				if (newV.length > 1){
					this.chatScroll()
				}
			}
		},
		onUnload() {
			let self = this
			self.sendChat({
				data: {
					cmd: '3',
					msg: '退出房间'
				},
				userAvatar: self.user_info.avatar,
				userName: self.userName || wx.getStorageSync('user_id'),
				cmd: "CustomCmdMsg"
			}, false)
			self.removeStore()
			setTimeout(() => {
				self.tim.logout().then(function(imResponse) {	
					console.log(imResponse.data, '登出成功....'); // 登出成功
				}).catch(function(imError) {
					console.warn('logout error:', imError);
				});
			}, 2000)
			self.ChangeOnline(self.ChangeStuts=4)//退出直播间把在线状态改为离线
		},
		methods: {
			ChangeOnline(){//进入直播间把在线状态改为在线
				let _this = this
				var data  ={
					group_id:_this.itemRoom.payRoomId,
					user_id:wx.getStorageSync('user_id'),
					status:_this.ChangeStuts
				}
				_this.myAjaxNewPost({
					model: 'message',
					controllerName: 'messageJoinGroup',
					actionName: 'updateStatus',
					data: data,
					successBack: function(res) {
						
					}					
				})
			},
			getonline(){//获取在线人数
				let _this = this
				var data  ={
					group_id:_this.itemRoom.payRoomId,
				}		
				_this.myAjaxNew({
					model: 'message',
					controllerName: 'messageJoinGroup',
					actionName: 'queryOnlineCount',
					data: data,
					successBack: function(res) {
						_this.itemRoom.onlineNum = res.data.data.onlineCount
						_this.onlinenums = _this.onlinenums.concat(res.data.data)
					}					
				})
			},
			getRoomMember() {
				let self = this
				this.myAjaxNew({
					model: 'message',
					controllerName: 'messageJoinGroup',
					actionName: 'queryListPage',
					data: {
						status:1,
						group_id:wx.getStorageSync('RoomID')
					},
					successBack: function(res) {
						if(self.isCaster) self.itemRoom.data = res.data.data;
						else self.itemRoom.data = res.data.data.slice(0,5)
					},
				})
			}, 
			onGroupGift() { 
				this.isGroupGift = !this.isGroupGift 
			},
			onSend() {
				var self = this;
				self.isShowNum = false
				self.isShowGift = false
				var pay_count = self.giftMoney * self.giftNum;
				if (pay_count > self.catCoin) {
					uni.showToast({
						title: '猫币不够呢',
						icon: 'none'
					})
					return
				}
				var data = {
					user_id: uni.getStorageSync('user_id'),
					type_id: self.typeId,
					type: 'gift',
					payment_id: self.paymentId,
					pay_count: pay_count,
					source: 'user',
					gift_count: self.giftNum,
					pay_id: self.itemRoom.payRoomId,
					is_group: self.isGroupGift
				}
				self.myAjaxNewPost({
					model: 'user',
					controllerName: 'userOrder',
					actionName: 'insert',
					data: data,
					successBack: function(res) {
						if (res.data.data == '订单完成') {
							console.log(res, '订单完成')
							var msg = {
									giftMsg:'送给全体成员见面礼',
									giftNum:self.giftNum,
									giftUrl:self.giftList[self.paymentId].pic
								}
							var TheGifts = {
								cmd: '6',
								msg:JSON.stringify(msg)
							}
							self.sendChat({
								cmd: "CustomCmdMsg",
								data:TheGifts,
								userAvatar: self.user_info.avatar,
								userName: self.userName || wx.getStorageSync('user_id'),
							}, false)
						}
					},
				})
			},
			onShowGift() {
				let self = this
				self.component = self.$mp.page.selectComponent("#id_liveroom");
				self.component.setBlack();
				self.isShowGift = true
			},
			onSendNum() {
				this.isShowNum = true
			},
			onGiftNum(num) {
				this.giftNum = num
				this.isShowNum = false
			},
			chooseGift(index, item) {
				this.menuIndex = index
				this.giftMoney = item.amount
				this.typeId = item.id
			},
			getgiftList() {
				var self = this;
				this.myAjaxNew({
					model: 'user',
					controllerName: 'userGift',
					actionName: 'query',
					data: '',
					successBack: function(res) {
						console.log(res, '礼物')
						self.giftList = res.data.data
						self.giftMoney = self.giftList[0].amount
					},
				})
			},

			isMutedPlayer() {
				// console.log('观众静音或者非静音')
				this.mutedPlayer = !this.mutedPlayer

			},
			isMutedPusher() {
				// console.log('主播禁麦或者非禁麦')
				this.mutedPusher = !this.mutedPusher
			},
			timingChat() {
				console.log('观众成为主播触发了没有？')
				let self = this
				let add = setInterval(() => {
					let closeAddress = wx.getStorageSync('closeAddress')
					if (closeAddress) {
						clearInterval(add)
					} else {
						console.log(JSON.parse(JSON.stringify(self.chatMixed)), '发送的信息')
						self.sendChat(JSON.parse(JSON.stringify(self.chatMixed)), true)
					}
				}, 1000)
			},
			IsInterviewWheat(){
				if(this.IsInterview == true){
					let self = this
					let date = (new Date()).valueOf()
					let toID = self.WeekToId.toString()
					let data ={
						cmd:"linkmicinvtier",
						data:{
							Invateindex:'',
							roomID:wx.getStorageSync('liveRoomID').toString(),
							type:'request',
							timestamp:date,
							userAvatar: wx.getStorageSync('avatar').toString(),
							userID:wx.getStorageSync('user_id').toString(),
							userName:wx.getStorageSync('nick_name').toString()
						}
					}
					console.log(data)
					self.component = self.$mp.page.selectComponent("#id_liveroom");
					let message = self.tim.createCustomMessage({
						to: toID,
						conversationType:'C2C',
						payload: {
							data: JSON.stringify(data),
							description: '',
							extension: '',
						},
					});
					let customPromise = self.tim.sendMessage(message);
				}
			},
			sendChat(chatText, isMiexd) {
				console.log(chatText)
				let self = this
				let date = new Date()
				let toID = wx.getStorageSync('liveRoomID').toString()
				self.component = self.$mp.page.selectComponent("#id_liveroom");
				let message = self.tim.createCustomMessage({
					to: toID,
					conversationType: TIM.TYPES.CONV_GROUP,
					payload: {
						data: self.cleanText(chatText),
						description: '',
						extension: '',
					}
				});
				// console.log(self.chatMixed, '观众接受的混流信息')
				let customPromise = self.tim.sendMessage(message);
				customPromise.then(function(imResponse) {
					// 发送成功
					console.log(imResponse.data.message, '成功？')
					if (!isMiexd) {//这里是自己发的信息显示在聊天屏幕里
						let userO = imResponse.data.message.payload.data ? JSON.parse(imResponse.data.message.payload.data) : imResponse.data.message.payload.text
						console.log(userO,'2288882')
						if(userO.data.cmd == 2){//提示有人进入房间
							self.chatList.push({
								name: userO.userName,
								ishow:userO.data.cmd,
								message:userO.data.msg,
							})
						}else if(userO.data.cmd == 3){//提示有人退出房间
							self.chatList.push({
								name: userO.userName,
								ishow:userO.data.cmd,
								message: userO.data.msg,
							})
						}else if(userO.data.cmd == 5 || userO.data.cmd == 1){//文本消息
							self.chatList.push({
								ishow:userO.data.cmd,
								name: userO.userName,
								userAvatar:userO.userAvatar,
								message: userO.data.msg,
							})
						}else if(userO.data.cmd == 6){//礼物消息
							var thegift=JSON.parse(userO.data.msg);
							console.log(thegift['giftMsg'],'2288882000')
							self.chatList.push({
								ishow:userO.data.cmd,
								name: userO.userName,
								giftMsg:thegift['giftMsg'],
								giftNum:thegift['giftNum'],
								giftUrl:thegift['giftUrl'],
							})
						}
						// self.component.onRecvRoomTextMsg({
						// 	userName: self.user_info.nick_name || self.user_info.mobile.slice(7),
						// 	message: userO.data.msg,
						// 	time: date.getHours() + ':' + date.getMinutes()
						// })
						self.chat = ''
					}
				}).catch(function(imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
			},
			cleanText(text, josnFormat) {
				let self = this
				if (josnFormat == 'jsonParse') {
					text.msg = JSON.parse(text.msg)
					let keys = Object.keys(text.msg)
					let values = Object.values(text.msg)
					let newValues = []
					keys.forEach(key => {
						if (text.msg[key]) {
							text.msg[key] = JSON.parse(text.msg[key])
						} else {
							wx.setStorageSync('pushers', true)
						}
					})
					values.forEach(value => {
						if (value != '""') {
							newValues.push(value)
						}
					})
					// console.log(newValues, '看看是不是最新的？？？？？？')
					// console.log(newKeys, '这个数组里面是不是都是最新的')
					newValues.length == 2 && !self.smallCaster ? self.canvasAud = 'audience' : '';
					newValues.length >= 3 && self.smallCaster ? self.canvasAud = 'audience' : '';
					return text
				} else if (text.cmd == 'CustomCmdMsg') {
					return JSON.stringify(text)
				} else {
					let keys = Object.keys(text.msg)
					keys.forEach(key => {
						text.msg[key] = JSON.stringify(text.msg[key])
					})
					text.msg = JSON.stringify(text.msg)
					return JSON.stringify(text)
				}
			},
			sendButton() {
				if (this.chat) {
					this.inputBlur()
					this.sendChat({
						data: {
							cmd: '5',
							msg: this.chat
						},
						userAvatar: this.user_info.avatar,
						userName: this.userName || wx.getStorageSync('user_id'),
						cmd: "CustomCmdMsg"
					}, false)

				}
			},
			inputEnd(e) {
				if (/hideinp/.test(e.detail.animationName)) {
					this.isBut = true
				}
			},
			imgFocus() {
				this.isFocus = true
				this.isBut = false
			},
			inputBlur() {
				this.isFocus = false
			},
			chatScroll() {
				let _this = this
				setTimeout(()=>{
					const query = uni.createSelectorQuery().in(_this);
					query.selectAll('#scrollview').boundingClientRect(function(res){
						    _this.chatTop = 50
					}).exec()
				},2000)					
			},
			linkIM() {
				let self = this
				self.onTIM()
				wx.setStorageSync('addressNumber', [0, 0, 0, 0, 0])
				let id = uni.getStorageSync('user_id') || 0
				let sig = uni.getStorageSync('user_sign') || 0
				if (id && sig) {
					self.loginIM()
				} else {
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tabBer/CrossBorder/CrossBorder'
						})
					}, 3000)
					uni.showToast({
						title: '请登录',
						icon: 'none'
					})
					// 后续添加假账号，来让未登录用户观看直播但不可发消息
				}
			},
			onTIM() {
				let self = this
				this.tim = TIM.create({
					SDKAppID: '1400255047'
				})
				this.tim.setLogLevel(1)
				wx.$app = this.tim
				wx.$app.myAjaxNew = self.myAjaxNew
				this.tim.registerPlugin({
					'cos-wx-sdk': COS
				})
				this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
					let toGroup = uni.getStorageSync('liveRoomID')
					let toUser = uni.getStorageSync('user_id')
					console.log(event.data[0], '收到消息了吗');
					console.log("本地获取liveroomID",toGroup);
					if(toGroup == event.data[0].to || toUser == event.data[0].to){//判断当前消息是否属于当前直播间的,或是否是当前观众
					//收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
						console.log("是当前直播间");
						self.onMessage(event)
					}				
				});
				// this.tim.on()
				this.tim.on(TIM.EVENT.SDK_READY, function(event) {
					// 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
					// event.name - TIM.EVENT.SDK_READY
					console.log(event, '1')
				});

				this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
					// 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
					// event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
					// event.data - 存储 Conversation 对象的数组 - [Conversation]
					console.log(event, '2')
				});

				this.tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
					// 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
					// event.name - TIM.EVENT.GROUP_LIST_UPDATED
					// event.data - 存储 Group 对象的数组 - [Group]
					console.log(event, '3')
				});

				this.tim.on(TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED, function(event) {
					// 收到新的群系统通知
					// event.name - TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED
					// event.data.type - 群系统通知的类型，详情请参见 GroupSystemNoticePayload 的 <a href="https://imsdk-1252463788.file.myqcloud.com/IM_DOC/Web/Message.html#.GroupSystemNoticePayload"> operationType 枚举值说明</a>
					// event.data.message - Message 对象，可将 event.data.message.content 渲染到到页面
					console.log(event, '4')
				});

				this.tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
					// 收到自己或好友的资料变更通知
					// event.name - TIM.EVENT.PROFILE_UPDATED
					// event.data - 存储 Profile 对象的数组 - [Profile]
					console.log(event, '5')
				});

				this.tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
					// 收到黑名单列表更新通知
					// event.name - TIM.EVENT.BLACKLIST_UPDATED
					// event.data - 存储 userID 的数组 - [userID]
					console.log(event, '6')
				});

				this.tim.on(TIM.EVENT.ERROR, function(event) {
					// 收到 SDK 发生错误通知，可以获取错误码和错误信息
					// event.name - TIM.EVENT.ERROR
					// event.data.code - 错误码
					// event.data.message - 错误信息
					console.log(event, '7')
				});

				this.tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
					// 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
					// event.name - TIM.EVENT.SDK_NOT_READY
					console.log(event, '8')
				});

				this.tim.on(TIM.EVENT.KICKED_OUT, function(event) {
					// 收到被踢下线通知
					// event.name - TIM.EVENT.KICKED_OUT
					// event.data.type - 被踢下线的原因，例如 TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多账号登录被踢
					console.log(event, '9')
				});
			},
			loginIM() {
				let self = this
				let promise = self.tim.login({
					userID: uni.getStorageSync('user_id').toString(),
					userSig: uni.getStorageSync('user_sign')
				});
				promise.then(function(imResponse) {
					wx.setStorageSync('isTIM', true)
				}).catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tabBer/CrossBorder/CrossBorder'
						})
					}, 3000)
					uni.showToast({
						title: '网络错误，请刷新重试1',
						icon: 'none'
					})

				});
			},

			onMessage(options) {
				let self = this;
				let user = options.data
				console.log(user,'哈哈')
				let streamIdArray = wx.getStorageSync('streamIdArray')
				let isCaster = wx.getStorageSync('isCaster')
				self.component = self.$mp.page.selectComponent("#id_liveroom");
				
				user.forEach(item => {
					// user[0]
					let userO = item.payload.data ? JSON.parse(item.payload.data) : item.payload.text;
					console.log(item.payload.data);
					console.log(userO.cmd);
					if (userO.cmd == 'linkmic') {
						// 处理连麦C2C请求
						console.log('来到这里', userO)
						self.receiveC2CMsg(userO)
					} else if(userO.cmd == "linkmicinvtier"){
						uni.showModal({
						    title: '提示',
						    content: '老师邀请你加入',
							cancelText:'拒绝',
							confirmText:'接受',
						    success: function (res) {//观众接受连麦
						        if (res.confirm) {
									var C2CMsg = {
										data:{
											result:'accept',
											type:'response'
										}
									}
						            self.receiveC2CMsg(C2CMsg)
						        } else if (res.cancel) {//观众拒绝连麦
						            var C2CMsg = {
						            	data:{
						            		result:'reject',
						            		type:'response'
						            	}
						            }
						            console.log(C2CMsg.data,'这是模拟数据')
						            self.receiveC2CMsg(C2CMsg)
						        }
						    }
						});
					}else if (userO.cmd == "RoomState") {//主播开播提醒
						uni.showModal({
						    title: '主播开播了',
						    content: '课程已开启,观看',
							confirmText:'观看',
							success: function (res) {//观众接受连麦
							    if (res.confirm) {
									self.start()
							    } 
							}
						})
					}else if(userO.cmd == "notifyPusherChange"){//主播退播后停止推流
						uni.showModal({
						    title: '主播下播了',
						    content: '主播已经下拨了',
							confirmText:'好的',
							success: function (res) {//观众接受连麦
							    if (res.confirm) {

							    } 
							}
						})
					}else if (userO.cmd == "CustomCmdMsg") {
						console.log(userO,'9090')
						var userAvatar =  userO.userAvatar
						var message = userO.data.msg
						if (typeof userO.data.msg == 'string') {//判断是弹幕还是礼物弹幕						
							if(userO.data.cmd == 2){//提示有人进入房间
								self.getRoomMember()//获取在线人数头像
								self.itemRoom.onlineNum++//在线人数加一
								if(userO.data.msg == ''){
									self.chatList.push({
										name: userO.userName,
										ishow:userO.data.cmd,
										message: '进入房间',
									})
								}else{
									self.chatList.push({
										name: userO.userName,
										ishow:userO.data.cmd,
										message: userO.data.msg,
									})
								}
							}else if(userO.data.cmd == 3){//提示有人退出房间
								self.getRoomMember()//获取在线人数头像
								self.itemRoom.onlineNum--//在线人数减一
								if(userO.data.msg == ''){
									self.chatList.push({
										name: userO.userName,
										ishow:userO.data.cmd,
										message: '退出房间',
									})
								}else{
									self.chatList.push({
										name: userO.userName,
										ishow:userO.data.cmd,
										message: userO.data.msg,
									})
								}
								
							}else if(userO.data.cmd == 5 || userO.data.cmd == 1){//文本消息
								self.chatList.push({
									ishow:userO.data.cmd,
									name: userO.userName,
									userAvatar:userAvatar,
									message: message,
								})
							}else if(userO.data.cmd == 6){//礼物消息
								var thegift=JSON.parse(message);
								self.chatList.push({
									ishow:userO.data.cmd,
									name: userO.userName,
									userAvatar:userAvatar,
									giftMsg:thegift['giftMsg'],
									giftNum:thegift['giftNum'],
									giftUrl:thegift['giftUrl'],
								})
							}
						}
					} else if (userO.cmd == 'AnchorIndex') {
						let addMixed;
						addMixed = self.cleanText(userO, 'jsonParse')
						self.chatMixed = addMixed
						console.log('赋值后的', self.chatMixed)
					} else if (userO.cmd == 'AnchorLock') {
						if (userO.msg.length > 0) userO.msg = JSON.parse(userO.msg);
						self.anchorLock = userO
						console.log(self.anchorLock, '改变后的')
					}
				})
			},
			receiveC2CMsg(C2CMsg) {
				let self = this
				let id = wx.getStorageSync('user_id')
				let isCaster = wx.getStorageSync('isCaster')
				if (C2CMsg.data.type == 'request' && C2CMsg.data.userID != id.toString()) {
					console.log(C2CMsg, '这是连麦消息');
					self.component.onRequestJoinAnchor({
						userID: C2CMsg.data.userID,
						userName: C2CMsg.data.userName,
						userAvatar: C2CMsg.data.userAvatar,
						joinIndex: C2CMsg.data.joinIndex
					});
					self.addNumber = C2CMsg.data.joinIndex
					wx.setStorageSync('number', C2CMsg.data.joinIndex)
				} else if (C2CMsg.data.type == 'response') {
					if (C2CMsg.data.result == 'accept') {
						console.log("response? 收到主播同意连麦---", C2CMsg)
						let num = wx.getStorageSync('number')
						if (!isCaster) {
							let addressChat = {
								cmd: "AnchorIndex",
								msg: {},
							}
							addressChat.msg[num] = {
								avatar: self.user_info.avatar,
								userId: wx.getStorageSync("user_id").toString(),
								nickName: self.userName || wx.getStorageSync("user_id").toString()
							}
							wx.setStorageSync('requestLinking', false)
							self.smallCaster = true
							self.sendChat(addressChat, true)
							self.component.link();
							self.isLink = !self.isLink
						}
						let addressNumber = wx.getStorageSync('addressNumber')
						addressNumber.splice(self.addNumber - 2, 1, self.addNumber)
						wx.setStorageSync('addressNumber', addressNumber)

					} else if (C2CMsg.data.result == 'reject') {
						console.log("主播拒绝了", C2CMsg)
						wx.setStorageSync('requestLinking', false)
						if (!isCaster) {
							self.onRoomEvent({
								detail: {
									tag: 'error',
									code: -9004,
									detail: C2CMsg.data.reason
								}
							})
						}

					}
				} else if (C2CMsg.data.type == 'kickout' && self.role != 'anchor') {
					self.component.exitLink()
					self.isLink = !self.isLink
				}
			},
			start: function() {
				var self = this;
				let isTIM = wx.getStorageSync('isTIM')
				if (isTIM) {
					self.component = self.$mp.page.selectComponent("#id_liveroom");
					console.log("是否开播",self.isStart);
					if (self.isStart) {
						self.component.start();  //到mlvbliveroomview.js 772行
						// self.sendChat({
						// 	data: {
						// 		cmd: 'RoomState',
						// 		msg: 'ClassStar'
						// 	},
						// 	userAvatar: this.user_info.avatar,
						// 	userName: this.userName || wx.getStorageSync('user_id'),
						// 	cmd: "RoomState"
						// }, false)
					} else {
						self.component.stop();
						wx.setStorageSync('closeAddress', true)
					}
					self.isStart = !self.isStart;
				} else {
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tabBer/CrossBorder/CrossBorder'
						})
					}, 3000)
					uni.showToast({
						title: '网络错误，请刷新重试tim',
						icon: 'none'
					})
				}
			},
			// 连麦
			onLinkClick: function() {
				var self = this;
				self.component && self.component.requestJoinAnchor();
			},

			onRoomEvent: function(e) {
				var self = this;
				var args = e.detail;
				console.log('\n\n--onRoomEvent', args,'\n\n')
				switch (args.tag) {
					case 'roomClosed':
						{
							wx.showModal({
								content: `房间已解散`,
								showCancel: false,
								complete: () => {
									wx.navigateBack({
										delta: 1
									})
								}
							});
							break;
						}
					case 'error':
						{
							wx.showToast({
								title: args.detail,
								icon: 'none',
								duration: 1500
							})
							if (args.code == 5000) {
								console.error('code等于5000')
							} else if (args.code == -9003){
								wx.showToast({
									title: '主播不在线',
									icon: 'none',
									duration: 1500
								})
							}
							else {
								console.error("收到error:", args)
								if (args.code != -9004) {
									setTimeout(() => {
										self.isStart = !self.isStart
									}, 1000)
								}
							}
							break;
						}
					case 'linkOn':
						{ //连麦观众在连麦成功时会收到此通知
							// 连麦(观众) 0.16 连麦成功
							console.log("连麦成功....")
							break;
						}
					case 'linkOut':
						{ //连麦断开
							console.log("退麦成功....")
							break;
						}
					case 'recvTextMsg':
						{
							// 推送全员收到文本消息 -2.8(文本聊天消息)
							// console.log('主播收到消息:', e.detail.detail);
							self.chatList.push({
								name: e.detail.detail.userName,
								message: e.detail.detail.message
							})
							break;
						}
					case 'requestJoinAnchor':
						{ //连麦(主播) 0.6 收到连麦请求
							var jioner = args.detail;
							var showBeginTime = Math.round(Date.now());
							console.log("接受连麦请求");
							wx.showModal({
								content: jioner.userName + '请求连麦',
								cancelText: '拒绝',
								confirmText: '接受',
								success: function(sm) {
									var timeLapse = Math.round(Date.now()) - showBeginTime;
									if (timeLapse < 10000) {
										if (sm.confirm) {
											// 0.6.1 同意触发事件(根方法在mlvbliveroomview.js)
											self.component && self.component.respondJoinAnchor(true, jioner);
											let num = wx.getStorageSync('number')
											self.imgAddress.splice(num - 2, 1, true)
										} else if (sm.cancel) {
											// 0.6.2 拒绝触发事件
											self.component && self.component.respondJoinAnchor(false, jioner);
										}
									} else {
										wx.showToast({
											title: '连麦超时',
										})
									}
								}
							})
							break;
						}
					case 'hideButton':
						{

							if (args.detail) {
								self.isZoom = true;
							} else {
								self.isZoom = false;
							}

							break
						}
					case 'created':
						{
							console.log('定时器开启群群群群群群创建成功 ', e)
							self.timingChat()
							break;
						}
					case 'hideGift':
						{
							if (args.detail.isGift) {
								self.isShowGift = true;
								self.paymentId = args.detail.payment_id
							} else {
								self.isShowGift = false;
								self.isShowNum = false
							}

							break
						}
					case 'start':
						{
							self.start() //到819行
							break
						}
					case 'player':
						{
							self.isMutedPlayer()
							break
						}
					case 'pusher':
						{
							self.isMutedPusher()
							break
						}
					case 'chat':
						{
							self.imgFocus()
							break
						}
				}
			},

			removeStore: function() {
				console.log('开始销毁定时器和临时数据')
				// wx.setStorageSync('accountInfo', {})
				// wx.setStorageSync('closeAddress', true)
				wx.removeStorage({
					key: 'liveRoomID'
				})
				wx.removeStorage({
					key: 'RoomID'
				})
				wx.removeStorage({
					key: 'liveAnchorID'
				})
				// wx.removeStorage({key: 'msgType'})
				wx.removeStorage({
					key: 'isTIM'
				})
				// wx.removeStorage({key: 'isIM'})
				// wx.removeStorage({key: 'loginCtx'})
				wx.removeStorage({
					key: 'streamIdArray'
				})
				wx.removeStorage({
					key: 'number'
				})
				wx.removeStorage({
					key: "isCaster"
				})
				wx.removeStorage({
					key: "addressNumber"
				})
				wx.removeStorage({
					key: 'requestLinking'
				})
				wx.removeStorage({
					key: 'pushers'
				})
				// this.chatMixed = {
				// 	cmd: 'AnchorIndex',
				// 	msg: {
				// 		"0": {
				// 			avatar: self.user_info.avatar,
				// 			userId: wx.getStorageSync('user_id').toString(),
				// 			nickName: self.userName || wx.getStorageSync('user_id').toString()
				// 		}
				// 	}
				// }
			}

		}
	}
</script>

<style scoped>
	.mlvb-boss {
		height: 100%;
		background-color: #393F3F;

	}

	.cat-gift {
		z-index: 99999999999999;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 700rpx;
		background-color: #fff;
		padding: 0 0 5rpx 5rpx;
	}

	.gift-num {
		border: 1px solid #47CECF;
		background-color: #fff;
		width: 100rpx;
		height: 400rpx;
		position: absolute;
		right: 150rpx;
		bottom: 100rpx;
		z-index: 666;
		border-radius: 10rpx;
		text-align: center;
		font-size: 30rpx;
	}

	.item-num {
		margin: 15rpx 0;
	}

	.cat-top {
		display: flex;
		justify-content: space-around;

		align-items: center;
		width: 97%;
		margin: 0 auto;
		padding: 27rpx 0rpx;
		border-bottom: 1px solid #E6E6E6;
	}

	.cat-top .item-top {
		width: 30%;
		text-align: center;
		color: #333333;
		font-size: 34upx;
	}

	.cat-top .item-top:nth-of-type(1) {
		display: flex;

		align-items: center;
	}

	.cat-top .item-top cover-view:nth-of-type(1) {
		color: #666666;
		font-size: 30upx;
	}

	.cat-top .item-top cover-view:nth-of-type(2) {
		font-size: 32upx;
	}

	.cat-top .item-top:nth-of-type(3) {
		display: flex;
		justify-content: flex-end;
	}

	.cat-top cover-image {
		width: 38upx;
		height: 38upx;
	}

	.gift {
		width: 100%;
		margin: 0 auto;
		height: 500rpx;
		overflow: auto;
		display: flex;
		flex-wrap: wrap;

	}

	.gift_item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 10upx;
		width: 19%;
		height: 210rpx;
		margin: 4rpx;
		font-size: 30rpx;
		color: #333333;
		box-sizing: border-box;
		position: relative;
	}

	.gift_item cover-image {
		width: 95upx;
		height: 95upx;
	}

	.text2 {
		font-size: 22rpx;
		color: #999999;
	}

	.active1 {
		color: #23b7cb;
		font-size: 15px;
		background: #fff;
		border: 1px solid #2EEA9D;
	}

	.send {
		width: 100%;
		margin: 0 auto;
		/* background-color: #FC6657; */
		height: 110rpx;
		line-height: 100rpx;
		display: flex;
		/* justify-content: space-between; */
		align-items: center;
		position: relative;
	}

	.item-send {
		width: 250rpx;
		height: 70rpx;
		border-radius: 40px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* background-color: #F7D4FF; */
		position: absolute;
		right: 20rpx;
		/* margin-right: 20rpx; */
		color: #47CECF;
		font-size: 30rpx;
		border: 1px solid #47CECF;
	}

	.item-send cover-image {
		width: 26rpx;
		height: 15rpx;

		margin-left: 20rpx;
	}

	.backRotate {
		transform: rotate(180deg);
	}

	.isRotate {
		transform: rotate(360deg);
	}

	.item-send cover-view:nth-of-type(1) {
		width: 30%;
		height: 100%;
		text-align: center;
		line-height: 70rpx;
	}

	.onSend {
		background-color: #47CECF;
		color: #FFFFFF;
		height: 100%;
		width: 50%;
		text-align: center;
		line-height: 70rpx;
	}

	.group-gift {
		position: absolute;
		left: 20rpx;
		display: flex;
		align-items: center;
		font-size: 30rpx;
	}

	.group-gift cover-image {
		width: 27rpx;
		height: 27rpx;
		margin-right: 10rpx;
	}

	.mlvb-layer {
		/* 64 */
		height: 100%;
		/* background-color: #00BCBB */
	}

	#id_liveroom {
		height: 100%;
		width: 100%;
	}

	.group-top-video {
		padding-top: 25upx;
		height: 40upx;
		background-color: #393F3F;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.left {
		display: flex;
		justify-content: space-around;
		align-items: center;
		font-size: 27upx;
		color: #fff;
	}

	.left view {
		margin: 0 10upx;
	}

	.right {
		font-size: 30upx;
		border-radius: 15upx;
		color: #fff;
		background-color: #47CECF;
		padding: 5upx;
		margin-right: 5px;
	}

	.group-top-voice {
		padding-top: 25upx;
		background-color: #393F3F;
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}

	.group-top-voice view {
		margin: 10upx;
		width: 30%;
		font-size: 27upx;
		color: #fff;
	}

	.voice-c {
		text-align: end;
	}

	.voice-right {
		position: relative;
	}

	.voice-right view {
		position: absolute;
		right: -15px;
		top: -13upx;
		font-size: 27upx;
		border-radius: 15upx;
		color: #fff;
		text-align: center;
		background-color: #47CECF;
		padding: 5upx;
	}

	.live-chat {
		width: 100%;
		/* background-color: #006EFF; */
		height: 21%;
		/* 26 */
		overflow: auto;
	}

	.item-chat {
		background-color: #000000;
		color: #FFFFFF;
		opacity: 0.7;
		border-radius: 5px;
		font-size: 26upx;
		font-family: PingFang-SC-Regular;
		font-weight: Regular;
		margin: 5px 0;
		margin-left: 10px;
		padding: 5px;
	}

	.big {
		width: 80%;
		display: flex;
	}

	.big .text-two {
		width: 80%;
		display: inline-block;
	}

	.small {
		margin: 5px 0;
		margin-left: 10px;
		display: flex;
		align-items: center;
	}

	.text-three {
		background-color: #000000;
		color: #FFFFFF;
		opacity: 0.7;
		border-radius: 5px;
		font-size: 26upx;
		font-family: PingFang-SC-Regular;
		font-weight: Regular;
		padding: 5px;
	}

	.show-view {
		animation-name: showinp;
		animation-duration: 1s;
		animation-fill-mode: forwards;
		display: flex;

	}

	@keyframes showinp {
		0% {
			opacity: 0;
		}

		25% {
			opacity: 0;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			opacity: 1;
			display: block;
		}
	}

	.hide-view {
		animation-name: hideinp;
		animation-duration: 0s;
		animation-fill-mode: forwards;
	}

	@keyframes hideinp {
		0% {
			opacity: 0.1;
		}

		100% {
			opacity: 0;
		}
	}

	.input-chat {
		border: 1px solid #F5B356;
		background-color: #FFFFFF;
		margin: 1px 0;
		width: 80%;
		height: 30rpx;
		margin-left: 5px;
		border-radius: 5px;
	}

	.send-chat {
		/* margin: 3px 0; */
		width: 15%;
		height: 60rpx;
		font-size: 25upx;
		line-height: 60rpx;
	}

	.show-button {
		animation-name: showbut;
		animation-duration: 1s;
		animation-fill-mode: forwards;
	}

	@keyframes showbut {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
			display: block;
		}
	}

	.mlvb-button {
		/* background-color: red; */
		width: 100%;
		display: flex;
		justify-content: space-between;

	}

	.start {
		margin: 15px;
	}

	.view-button {
		/* background-color: #E0813C; */
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 25%;
	}

	.view-button image {
		width: 70rpx;
		height: 70rpx;
	}

	.start-button {
		width: 93rpx;
		height: 93rpx;

	}
</style>
